//
//  QiNiuLogic.m
//  UniversalApp
//
//  Created by 志刚杨 on 2018/8/23.
//  Copyright © 2018年 voidcat. All rights reserved.
//

#import "QiNiuLogic.h"

@implementation QiNiuLogic

+(void)getQiniuTokenSuccess:(CommonBlock)block
{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"app_api" A:@"get_qiniu_upload_token"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [CYNET POSTv3:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        QiNiuInfoModel *model = [QiNiuInfoModel modelWithJSON:responseObject];
        if(block)
            block(model);
    } failure:^(NSString *error, NSInteger code) {
        [MBProgressHUD showTopTipMessage:error];
    } hasCache:NO];
}

+(void)QiNiuUplaodImage:(UIImage *)image WithQiuNiuInfo:(QiNiuInfoModel *)qiniuModel Block:(CommonBlock)block{
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    NSData *imageData = UIImagePNGRepresentation(image);
    
    [upManager putData:imageData key:[QiNiuLogic getQiNiuKeyWidthPex:@"idImage"] token:qiniuModel.token
              complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {

                  qiniuModel.fileKey = key;
                  NSLog(@"%@", info);
                  NSLog(@"%@", resp);
                  block(qiniuModel);
              } option:nil];
   
}

//七牛上传随机数key
+(NSString *)getQiNiuKeyWidthPex:(NSString *)pex
{
    return [NSString stringWithFormat:@"%@/%@%d.png",pex,[self getNowTimeTimestamp],[QiNiuLogic getRandomNumber:0 to:1000]];
}

+(NSString *)getNowTimeTimestamp{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    return timeSp;
    
}

+(int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from + (arc4random() % (to - from + 1)));
}
@end
